import { createStore } from 'vuex'
import main from "../main";//main.ts文件中要暴露app
import router from '@/router';// 引入vuex
export default createStore({
  state: {
    topics: [],//订阅话题
  },
  mutations: {
    //mqtt服务
    MQTT_SERVICE(state, event){
      // mqtt连接成功
      main.config.globalProperties.$mqtt.on('connect', (e) => {
        console.log('连接成功:', e)
        // console.log(state.topics)
        main.config.globalProperties.$mqtt.subscribe(state.topics, { qos: 1 }, (error) => {
          if (!error) {
            console.log('订阅成功')
          } else {
            console.log('订阅失败')
          }
        })
      })
      // 接收消息处理
      main.config.globalProperties.$mqtt.on('message', (topic, message) => {
        console.log('收到来自', topic, '的消息', message.toString())
      })
      // 断开发起重连
      main.config.globalProperties.$mqtt.on('reconnect', (error) => {
        console.log('正在重连:', error)
      })
      // 链接异常处理
      main.config.globalProperties.$mqtt.on('error', (error) => {
        console.log('连接失败:', error)
      })
    },
    //发布消息
    MQTT_PUBLISH(state, {topic, msg}){
      console.log(topic)
      main.config.globalProperties.$mqtt.publish(topic, msg)
    },
    //断开MQTT
    MQTT_CLOSE(state, event){
      console.log('断开MQTT');
      main.config.globalProperties.$mqtt.end()
    },
  },
  actions: {
  },
  modules: {
  }
})
